package cn.ven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class Auth2ServerConfig extends
        AuthorizationServerConfigurerAdapter {

    @Autowired
    AuthenticationManager authenticationManagerBean;


    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.tokenKeyAccess("permitAll()")  //  /oauth/token
                .checkTokenAccess("permitAll()") //允许资源服务器访问授权服务器
                .allowFormAuthenticationForClients();
    }

    // 配置哪些 client_id client_secret
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        System.out.println("configure(ClientDetailsServiceConfigurer clients)");
        clients.inMemory()
                .withClient("sobook").secret(passwordEncoder.encode("223344"))
                .authorizedGrantTypes("password", "authorization_code",
                        "client_credentials", "implicit", "refresh_token")
                .scopes("all").accessTokenValiditySeconds(60*60*180);

    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //比对client_id 和 client_secret
        endpoints.authenticationManager(authenticationManagerBean);
    }
}
